'''
Created on Nov 17, 2011

@author: ctester
'''

import time
import re
import os
from types import *
import glob
import random
from time import gmtime, strftime
from Instruments import *

import appscript
import aem
from appscript import *
import hmlme



home = os.getenv('HOME')
ts = None


def launchInstruments():
    ins = Instruments()
    
    wins = ins.resolveTarget('windows')
    if wins == None:
        pass
    elif len(wins.get()) == 0:
        ins.close();
    elif True == ins.getAttr('windows["Instruments[0-9]*"].buttons[1]', 'AXEnabled'):
        ins.click('windows["Instruments[0-9]*"].buttons[1]')
        sv = ins.resolveTarget('windows["Instruments[0-9]*"].sheets[1].buttons["Don[^\x00-\x7f]*t Save"]')
        if sv != None:
            ins.click(sv)
            time.sleep(1)
        ins.close()
    else:
        pass
    
        
#    bcls = ins.getAttr('windows["Instruments43"].buttons[1]', 'AXEnable')
        
    # launch Instruments
#    ins.close()
#    if ins.getProc() != None:
#        sv = ins.resolveTarget('windows["Instruments40"].sheets[1].buttons["Don[^\x00-\x7f]t Save"]')
#        if sv != None:
#            ins.click(sv)
#            time.sleep(1)
#    else:
#        print 'closed'
            
    ins.launch()
    ins.setFrontMost()
    
    # select template
    ins.click('windows["Instruments[0-9]*"].sheets[1].scroll_areas[2].outlines[1].rows[8].text_fields[1]')
    ins.click('windows["Instruments[0-9]*"].sheets[1].scroll_areas[3].UI_elements[1].images["Automation"]')
    ins.click('windows["Instruments[0-9]*"].sheets[1].buttons["Choose"]')
    ins.click('windows["Instruments[0-9]*"].buttons[2]')
        
def chooseScript(fn):
    ins = Instruments()
    
    ins.click('windows["Instruments[0-9]*"].splitter_groups[1].splitter_groups[1].scroll_areas[3].pop_up_buttons[1]')
    ins.click('windows["Instruments[0-9]*"].splitter_groups[1].splitter_groups[1].scroll_areas[3].pop_up_buttons[1].menus[1].menu_items["Choose Script[0-9a-zA-Z]*"]')
    ins.click('windows["Open"].groups[1].radio_groups[1].radio_buttons[2]')
        
    ins.keystroke('command+shift+h')
    __TA__ = ins.getChildrenWithAttri('windows["Open"].groups[1].splitter_groups[1].scroll_areas[2].outlines[1].rows[*].groups[1].static_texts[1]', 'AXFileName', home + '/__TA__')
    ins.dbClick(__TA__)

    scripts = ins.getChildrenWithAttri('windows["Open"].groups[1].splitter_groups[1].scroll_areas[2].outlines[1].rows[*].groups[1].static_texts[1]', 'AXFileName', home + '/__TA__/scripts')
    ins.dbClick(scripts)
    
    ta_js = ins.getChildrenWithAttri('windows["Open"].groups[1].splitter_groups[1].scroll_areas[2].outlines[1].rows[*].static_texts[1]', 'AXFileName', home + '/__TA__/scripts/' + fn)
    ins.dbClick(ta_js)


def chooseTarget():
    ins = Instruments()
    ins.click('windows["Instruments[0-9]*"].tool_bars[1].groups[2].groups[1].radio_groups[1].menu_buttons[1]')
    ins.keystroke('choose')
    ins.keyCode('36')
    time.sleep(1)
    ins.keyCode('36')
    ins.click('windows["Instruments[0-9]*"].sheets[1].scroll_areas[2].outlines[1].rows[3].text_fields[1]')
#    ins.click('windows["Instruments[0-9]*"].sheets[1].browsers[1].scroll_areas[1].scroll_areas[1].lists[1].text_fields[1]')
    tag = ins.getChildrenWithAttri('windows["Instruments45"].sheets[1].browsers[1].scroll_areas[1].scroll_areas[1].lists[1].text_fields', 'AXValue', 'TestView.app')
    ins.click(tag)
    ins.click('windows["Instruments[0-9]*"].sheets[1].buttons["Choose"]')
    
def runScript():
    ins = Instruments()
    ins.click('windows["Instruments[0-9]*"].tool_bars[1].groups[1].groups[1].checkboxes[2]')
    while True:
        en = ins.getAttr('windows["Instruments[0-9]*"].splitter_groups[1].splitter_groups[1].scroll_areas[3].buttons["Start Script"]', 'AXEnabled')
        if en == True:
            break
        time.sleep(2)
        
    ins.click('windows["Instruments[0-9]*"].tool_bars[1].groups[1].groups[1].checkboxes[2]')
    
def saveLog():
    print 'asd---s'
    ins = Instruments()
    ins.click('windows["Instruments[0-9]*"].splitter_groups[1].splitter_groups[1].scroll_areas[3].buttons["Export All Results Now[^\x00-\x7f]*"]')
    ins.click('windows["Export"].groups[1].radio_groups[1].radio_buttons[2]')
    print 'asd---e'    
    ins.keystroke('command+shift+h')
    __TA__ = ins.getChildrenWithAttri('windows["Export"].groups[1].splitter_groups[1].scroll_areas[2].outlines[1].rows[*].groups[1].static_texts[1]', 'AXFileName', home + '/__TA__')
    ins.dbClick(__TA__)

    results = ins.getChildrenWithAttri('windows["Export"].groups[1].splitter_groups[1].scroll_areas[2].outlines[1].rows[*].groups[1].static_texts[1]', 'AXFileName', home + '/__TA__/tmp')
    ins.dbClick(results)
    
    ins.click('windows["Export"].buttons["Open"]')
    
def getTimeStamp():
    return strftime('%Y-%m-%d_%H-%M-%S_', gmtime()) + str(random.randint(100, 999))

def renameLog(bfn):
    if os.path.exists(home + '/__TA__/tmp/Automation Results.plist'):
        print ts
        os.system('mv ' + home + '/__TA__/tmp/Automation\ Results.plist ' + home + '/__TA__/results/' + ts + '/' + bfn + '.plist')

def main():
    global ts
    ts = getTimeStamp()
    os.system('mkdir ' + home + '/__TA__/results/' + ts)
    ins = Instruments()
    ins.setFrontMost()
        
    # launch Instruments
    launchInstruments()
        
    # choose target
    chooseTarget()
        
    # run scripts, save logs
    path = home + '/__TA__/scripts/*.js'
    for f in glob.glob(path):
        bfn = os.path.basename(f)
        
        print 'a'
        # choose script
        chooseScript(bfn)
        
        # run
        runScript()
        
        # save log to tmp
        saveLog()
        
        # rename log
        renameLog(bfn)
        
        print 'b'
        # wait 5 seconds
        time.sleep(5)

try:
    main()
#    ins = Instruments()
#    ins.setFrontMost()
#    saveLog()

#    if 1 == 1:
#        ins = Instruments()
#        print ins.getAttr('windows["Instruments[0-9]*"].splitter_groups[1].splitter_groups[1].scroll_areas[3].buttons["Start Script"]', 'AXEnabled')
except Exception as e:
    print e
    

#ins = Instruments()
#print int(ins.getAttr('windows["Instruments[0-9]*"].buttons[1]', 'AXEdited'))
        

    
